package com.emip.servlet.report;

import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.emip.bean.MonthStoreBean;
import com.emip.pojo.Report;
import com.emip.pojo.Table;
import com.emip.service.MonthStoreService;
import com.emip.util.TableFormat;


@Controller
@RequestMapping(value="/report/month")
public class MonthReportAction extends ReportAction {

	@Autowired
	MonthStoreService monthStoreService;
	
	@RequestMapping(value="/show")
	public ModelAndView index() {
		return new ModelAndView("/report/report", setDefaultParams(mmap));
	}
	
	@RequestMapping(value="/data", method=RequestMethod.POST)
	@ResponseBody
	public Table<Map<String, Object>> getData(
			@RequestParam("startYear") int startYear, 
			@RequestParam("startMonth") int startMonth,
			@RequestParam("endYear") int endYear, 
			@RequestParam("endMonth") int endMonth,
			@RequestParam("siteId") String siteId,
			@RequestParam("itemIds[]") String[] itemIds,
			@RequestParam("siteItems[]") int[] siteItemIds,
			@RequestParam("page") int page,
			@RequestParam("rows") int size) {
		List<MonthStoreBean> result = monthStoreService.getByTimespan(startYear, startMonth, endYear, endMonth, itemIds, siteId, page, size);
		long records = monthStoreService.getCount(startYear, startMonth, endYear, endMonth, itemIds, siteId);
		long totalPages = records / size + (records % size == 0 ? 0 : 1);
		Report report = formatReportBody(result);
		return new TableFormat<Map<String, Object>>().formTable(totalPages, page, records, report.getBodys());
	}
			
	@RequestMapping(value="/statistic", method=RequestMethod.POST)
	@ResponseBody
	public Report getStatistic(
			@RequestParam("startYear") int startYear, 
			@RequestParam("startMonth") int startMonth,
			@RequestParam("endYear") int endYear, 
			@RequestParam("endMonth") int endMonth,
			@RequestParam("siteId") String siteId,
			@RequestParam("itemIds") String[] itemIds,
			@RequestParam("siteItems") int[] siteItemIds,
			HttpSession session) 
			throws ParseException {
		Report report = formatReport(
				monthStoreService.getByTimespan(startYear, startMonth, endYear, endMonth, itemIds, siteId),
				siteItemIds, session);
		return report;
	}
}
